package org.surelink.radius.console;


import org.surelink.radius.cache.UserCache;
import org.surelink.radius.console.message.Request;
import org.surelink.radius.console.message.RespBase;
import org.surelink.radius.console.message.Response;
import de.tototec.cmdoption.CmdOption;
import de.tototec.cmdoption.CmdlineParser;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class UserMetaProcess extends BaseProcess
{

    @Autowired
    private UserCache userCache;

    class Config
    {

        @CmdOption(names = {"--help"}, description = "打印帮助", isHelp = true)
        private boolean help;

        @CmdOption(names = {"set"}, description = "设置用户属性")
        private boolean set;

        @CmdOption(names = {"get"}, description = "查询用户属性")
        private boolean get;

        @CmdOption(names = {"usermeta"}, description = "新增用户命令", hidden = true)
        boolean setumeta;

        @CmdOption(names = {"--username", "-u"}, args = {"userName"}, minCount = 1, description = "用户上网账号")
        String username;

        @CmdOption(names = {"--metas", "-m"}, args = {"name", "value"}, minCount = 1, maxCount = -1, description = "用户属性： 属性名称 属性值")
        final Map<String, String> metas = new LinkedHashMap<String, String>();
    }

    public UserMetaProcess()
    {
        setOperate("usermeta");
    }

    @Override
    public Response process(Request req) throws IOException
    {
        Config config = new Config();
        CmdlineParser cp = new CmdlineParser(config);
        cp.setProgramName(getOperate());
        cp.parse(req.getCommand().split("\\s+"));

        if (config.help)
        {
            StringBuilder sb = new StringBuilder();
            cp.usage(sb);
            return new Response(RespBase.SUCCESS.getCode(), sb.toString());
        }

        if (config.set)
        {
            Map<String, String> metas = config.metas;
            for (Map.Entry<String, String> meta : metas.entrySet())
                userCache.setUserMeta(config.username, meta.getKey(), meta.getValue());

            return RespBase.SUCCESS;
        }
        else if (config.get)
        {
            Map<String, String> metas = userCache.getUserMetas(config.username);
            if (metas == null)
                return new Response(RespBase.NOT_EXIST_ERR.getCode(), "用户属性不存在");

            return new Response(metas);
        }

        return RespBase.MSG_FORMAT_ERR;

    }
}
